<template>
  <!-- 顶部导航栏 -->
  <van-nav-bar title="购物车页" left-text="返回" left-arrow placeholder fixed>
    <template #left>
      <div @click="$router.back()" v-if="canBack">
        <i class="van-badge__wrapper van-icon van-icon-arrow-left van-nav-bar__arrow"></i>
        <span data-v-5bff6dd4 class="van-nav-bar__text">返回</span>
      </div>
    </template>
    <template #right>
      <van-button
        text="删除选中"
        type="danger"
        size="small"
        @click="delChickedFn"
        :disabled="!someChecked"
      />
    </template>
  </van-nav-bar>
  <!-- 内容部分 -->
  <van-row v-for="item in newCartList" :key="item.inCartId">
    <!-- 左侧选择按钮 -->
    <van-col span="2">
      <div class="cart-checkbox">
        <van-checkbox v-model="item.checked" />
      </div>
    </van-col>
    <!-- 右侧商品卡片 -->
    <van-col span="22">
      <van-swipe-cell class="cart-item">
        <van-card
          :price="item.price"
          :desc="item.product.desc"
          :title="item.product.name"
          class="goods-card"
          :thumb="item.product.coverImage"
        >
          <!-- 在van-card中插入步进器到num位置 -->
          <template #num>
            <van-stepper
              v-model="item.amount"
              @plus="numPlusFn(item.product.id)"
              @minus="numMinusFn(item.product.id)"
            />
          </template>
        </van-card>
        <template #right>
          <van-button
            square
            text="删除"
            type="danger"
            class="delete-button"
            @click="deleteFn(item)"
          />
        </template>
      </van-swipe-cell>
    </van-col>
  </van-row>
  <!-- 底部活动局域栏 -->
  <van-submit-bar :price="price" button-text="提交订单" @submit="onSubmit" placeholder>
    <van-checkbox v-model="allChecked" @click="allCheckedFn" :disabled="allCheckedDisabled"
      >全选</van-checkbox
    >
    <!-- <template #tip>
      你的收货地址不支持配送, <span style="color: blue" @click="onClickAddress">修改地址</span>
    </template> -->
  </van-submit-bar>
</template>

<script setup>
//详情页进入可返回
let route = useRoute()
let canBack = ref(false)
if (route.query.back) {
  canBack.value = JSON.parse(route.query.back)
}

//
import { useCartStore } from '@/stores/cart'

const CartStore = useCartStore()

import { delProductFromCartReq, getCartListReq, postAddProductToCartReq } from '@/api/cart'
import { ref, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import { postProToOrderReq } from '@/api/order'
import { getUserInfoReq } from '@/api/user'
//获取购物车列表
let cartList = ref([])
let newCartList = ref([])
async function getCartList() {
  let res = await getCartListReq()
  console.log(res.data)
  cartList.value = res.data.data
  newCartList.value = cartList.value.map((item) => {
    return {
      inCartId: item.id,
      product: item.product,
      amount: item.amount,
      price: item.product.price,
      checked: false,
    }
  })
  // console.log(newCartList.value, 'newCartList')
}
getCartList()

let allChecked = ref(false)

function allCheckedFn() {
  // console.log('全选', allChecked.value)
  newCartList.value.forEach((item) => {
    item.checked = allChecked.value
  })
  // console.log(newCartList.value)
}
//单选双向绑定了不需要函数了，只需要判断是否全选=》watchEffect
// function checkedChangeFn() {
//   console.log('单选')
//   if (newCartList.value.length === 0) {
//     allChecked.value = false
//   } else {
//     allChecked.value = newCartList.value.every((item) => item.checked)
//   }
// }
let price = ref(0)
let someChecked = ref(false)
let allCheckedDisabled = ref(false)
watchEffect(() => {
  //判断是否全选
  if (newCartList.value.length === 0) {
    allCheckedDisabled.value = true
    allChecked.value = false
  } else {
    allCheckedDisabled.value = false
    allChecked.value = newCartList.value.every((item) => item.checked)
  }
  //计算总价
  price.value =
    newCartList.value
      .filter((item) => item.checked)
      .reduce((pre, cur) => {
        return pre + cur.price * cur.amount
      }, 0) * 100
  //判断是否有选中
  someChecked.value = newCartList.value.some((item) => item.checked)

  // 购物车列表变化时执行CartStore.getCartList()
  CartStore.getCartList()
})

//删除
function deleteFn(item) {
  delProductFromCartReq(item.inCartId).then((res) => {
    if (res.data.code === 1) {
      newCartList.value = newCartList.value.filter(
        (cartItem) => cartItem.inCartId !== item.inCartId,
      )
      // eslint-disable-next-line no-undef
      showToast('删除“' + item.product.name + '”成功')
    } else {
      // eslint-disable-next-line no-undef
      showToast('删除失败')
    }
    // console.log(res.data)
  })
}
//删除选中
function delChickedFn() {
  let delList = newCartList.value.filter((item) => item.checked)
  // console.log(delList)
  let p = []
  delList.forEach((item, index) => {
    p[index] = delProductFromCartReq(item.inCartId).then((res) => {
      if (res.data.code === 1) {
        newCartList.value = newCartList.value.filter(
          (cartItem) => cartItem.inCartId !== item.inCartId,
        )
      }
      // console.log(res.data)
    })
  })
  Promise.all(p).then(() => {
    // eslint-disable-next-line no-undef
    showToast('删除选中成功')
  })
}

//数量改变
function numPlusFn(productId) {
  postAddProductToCartReq(productId, 1).then((res) => {
    if (res.data.code == 1) {
      // eslint-disable-next-line no-undef
      showToast('数量增加成功')
    } else {
      // eslint-disable-next-line no-undef
      showToast('数量增加失败')
    }
  })
}
function numMinusFn(productId) {
  postAddProductToCartReq(productId, -1).then((res) => {
    if (res.data.code == 1) {
      // eslint-disable-next-line no-undef
      showToast('数量减少成功')
    } else {
      // eslint-disable-next-line no-undef
      showToast('数量减少失败')
    }
  })
}

async function onSubmit() {
  // eslint-disable-next-line no-undef
  showToast('提交订单')

  let addressStr = ''
  let receiver = ''
  let userInfoRes = await getUserInfoReq()
  // console.log(userInfoRes.data.data)

  receiver = userInfoRes.data.data.nickName
  addressStr = userInfoRes.data.data.address.replace(/\//g, '') + userInfoRes.data.data.area

  let orderList = newCartList.value.filter((item) => item.checked)

  console.log(orderList)

  let products = []
  //获取选中的商品信息products
  orderList.forEach((item, index) => {
    products[index] = { product: item.product.id, amount: item.amount }
  })

 let proToOrderres= await postProToOrderReq(products, receiver, addressStr)
    if (proToOrderres.data.code == 1) {


      // eslint-disable-next-line no-undef
      showSuccessToast(proToOrderres.data.msg)

      //删除已提交的订单
      orderList.forEach((item) => {
        delProductFromCartReq(item.inCartId).then((res) => {
          if (res.data.code === 1) {
            newCartList.value = newCartList.value.filter(
              (cartItem) => cartItem.inCartId !== item.inCartId,
            )
          }
          // console.log(res.data)
        })
      })
    }


    console.log(proToOrderres.data)
}

// function onClickAddress() {
//   // eslint-disable-next-line no-undef
//   showToast('修改地址')
// }
</script>

<style scoped>
:deep(.van-submit-bar) {
  bottom: 51px;
}

.goods-card {
  margin: 0;
  background-color: white;
}

.delete-button {
  height: 100%;
}

.cart-checkbox {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: white;
}
</style>
